<?php
namespace app\common\library;

use think\Exception;

class YuanfenjuService
{
    protected static $instance = null;
    protected $config;
    
    private function __construct()
    {
        $this->config = config('yuanfenju');
    }
    
    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }
    
    /**
     * 发送API请求
     * @param string $endpoint API端点
     * @param array $params 请求参数
     * @param string $method 请求方法
     * @return array
     * @throws Exception
     */
    public function request($endpoint, $params = [], $method = 'POST')
    {
        $url = $this->config['base_url'] . $endpoint;
        $params['api_key'] = $this->config['api_key'];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        } else {
            $url .= '?' . http_build_query($params);
            curl_setopt($ch, CURLOPT_URL, $url);
        }
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded'
        ]);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception("CURL Error: " . $error);
        }
        $result = json_decode($response, true);
        
        if (!$result) {
            return [
                'errcode' => -1,
                'errmsg' => 'Invalid JSON response'
            ];
        }
        
        return $result;
    }
}